package lib

import (
	"encoding/json"
	"fmt"
	"personal-skill/constants"
	"time"
)

type Time struct {
	time.Time
}

// MarshalJSON 序列化为JSON
func (t Time) MarshalJSON() ([]byte, error) {
	if t.IsZero() {
		return []byte("\"\""), nil
	}
	stamp := fmt.Sprintf("\"%s\"", t.Format(constants.DefaultTimePattern))
	return []byte(stamp), nil
}

// UnmarshalJSON 反序列化为JSON
func (t *Time) UnmarshalJSON(data []byte) error {
	var err error
	t.Time, err = time.Parse(constants.DefaultTimePattern, string(data)[1:20])
	return err
}

// 重写String
func (t *Time) String() string {
	marshal, _ := json.Marshal(t)
	return string(marshal)
}

// TranslateTimeFrom 从time.Time转化为lib.Time
func TranslateTimeFrom(time2 time.Time) Time {
	t := Time{}
	t.Time = time2
	return t
}
